
// var mongoose = require("../config/mongoConnection");
const mongoCollections = require('../config/mongoCollections');
const reviews = mongoCollections.reviews;
class Reviews {
  constructor() {
    this.typeSet = {
      title: String,
      reviewer: String,
      bookBeindReviewed: String,
      rating: Number,
      dateOfReview: String,
      review: String
    }
    this.validationList = {
      title: "string",
      reviewer: "string",
      bookBeindReviewed: "string",
      rating: "number",
      dateOfReview: "string",
      review: "string"

    }
    // var reviews = new mongoose.Schema(this.typeSet)
    // this.Reviews = mongoose.model("reviews", reviews);
  }
  async validation(data) {
    for (let item in data) {
      for (let initem in this.validationList) {
        if (item === initem) {
          if (typeof data[item] != this.validationList[initem]) {
            console.log(data[item])
            return { flag: false, error: `${item} style is error` }
          }
        }
      }
    }

    return { flag: true }
  }
  async saveReviews(data) {
    try {
      const reviewCollection = await reviews();
      const newInsertInformation = await reviewCollection.insertOne(data);
      // let Reviews = new this.Reviews(data)
      const result = await newInsertInformation.save()
      return result

    } catch (err) {
      return err
    }

  }
  async deleteAllReviews(id){
    try {
      
      const reviewCollection = await reviews();
      const Information = await reviewCollection.find({bookBeindReviewed:id})
      // let result = await this.Reviews.find({bookBeindReviewed:id})
      Information.forEach(async(item)=>{
       await reviewCollection.remove({"_id" :item._id})
      })
      setTimeout(() => {
        return "delete success"
      }, 2000);
     
    } catch (err) {
      return err
    }
  }
  async findAll(id) {
    try {
      const reviewCollection = await reviews();
      const Information = await reviewCollection.find({bookBeindReviewed:id})
      // let result = await this.Reviews.find({bookBeindReviewed:id})
      return Information

    } catch (err) {
      return err
    }
  }
  async deleteOneReview(id){
    try{
      const reviewCollection = await reviews();
      const Information = await reviewCollection.deleteOne({_id:id})
      // let result = await this.Reviews.deleteOne({_id:id})

      return `${id} is delete success`
    }catch(err){

    }
  }
  async findOneReview(reviewid){
    try {
      const reviewCollection = await reviews();
      const Information = await reviewCollection.findOne({_id:reviewid})
      // let result = await this.Reviews.findOne({_id:reviewid})
      return Information

    } catch (err) {
      return err
    }
  }
}

module.exports = new Reviews